package net.oschina.oldpig.sewer

import javafx.scene.image.Image
import javafx.scene.media.{Media, MediaPlayer}
import net.liftweb.json._

case class Bag(index: Int, media: Media, stream: ParleysStream)

trait SewerModel {
  implicit val formats = DefaultFormats

  val pkgLoader: JarClassLoader
  lazy val imageCache = collection.mutable.Map.empty[Int, Image]
  lazy val assets = parse(io.Source.fromInputStream(pkgLoader.getResourceAsStream("assets.json")).mkString)
  lazy val slides: List[Slide] = (assets \ "slides").extract[List[Slide]]
  lazy val streams = (assets \ "streams").extract[List[ParleysStream]]

  val players = collection.mutable.Map.empty[Int, MediaPlayer]

  def retrievePlayer(index:Int) = {
    players.get(index).getOrElse{
      println(s"Create #$index")
      val player = new MediaPlayer(bags(index).media)
      players(index) = player
      player
    }
  }

  lazy val bags: List[Bag] = {
    for ((stream, i) <- streams.zipWithIndex) yield Bag(i,
      new Media(pkgLoader.getResource(stream.local).toExternalForm),
      stream)
  }
  lazy val overallDuration: Double = bags.map(_.stream.duration).sum
  var overallPosition: Double = -1

  var currentSlide = -1

  def durationToString(dur: Long) = {
    val millis = dur % 1000
    val left = dur / 1000
    val hour = left / 3600
    val minute = left % 3600 / 60
    val second = (left % 3600) % 60
    f"$hour%02d:$minute%02d:$second%02d.$millis%03d"
  }

  def formatTime(elapsed: Long, duration: Long) = {
    def toStringWithoutMillis(dur: Long) = durationToString(dur).takeWhile(_ != '.')
    toStringWithoutMillis(elapsed) + "/" + toStringWithoutMillis(duration)
  }

}
